// 必买商品，用于优惠券和促销活动必买商品列表展示加购
// packageStore/pages/market/mustBuyProductList/mustBuyProductList.js
const app = getApp()
import BasePage from '../../../../js/common/base-page'
import {
  list,
  detail
} from '../../../../js/modules/mall'
import authorize from '../../../../js/modules/authorize'
import {
  api
} from '../../../../js/util'
import {
  isEmpty
} from '../../../../js/newUtil'

let locked = false

BasePage({
  pageKey: 'mustBuyProductList',
  /**
   * 页面的初始数据
   */
  data: {
    pageIndex: 1,
    pageSize: 20,
    hasMore: true,
    loaded: false,
    productList: [],
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    mainColor: api.titleColor || "#e56b14",
    Currency: api.Currency || '￥',
    isLogin: authorize.isLogin(),
    quantityDigits: 0,
    priceDigits: 2,
    decimalDigits: 2,
    listState: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      goodsIds: options.goodsIds
    })
    this.fasterComponent = this.selectComponent("#fasterComponent") // 多规格弹窗
    this.outofstock = this.selectComponent("#outofstock") // 缺货登记
    this.stockdistribution = this.selectComponent("#stockdistribution") // 库存分布
    this.getWholesaleConfig()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  getDataList() {
    let that = this
    let {
      pageIndex,
      pageSize,
      productList,
      goodsIds
    } = this.data
    let data = {
      PageIndex: pageIndex,
      PageSize: pageSize,
      goodsIds: goodsIds
    }
    list.loadGoodsList(data, function (res) {
      if (res.Success && !isEmpty(res.Content) && !isEmpty(res.Content.Data)) {
        productList = [...productList, ...res.Content.Data]
        that.setData({
          loaded: true,
          hasMore: true,
          productList
        })
        locked = false
        if (productList.length <= 10) {
          that.onReachBottom()
        }
      } else {
        that.setData({
          loaded: true,
          hasMore: false
        })
        locked = false
      }
    })
  },

  /**加载商品类的配置项参数 */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    list.getWholesaleConfigs(
      fkid,
      fkflag,
      (content) => {
        var fieldDisplayName = content.FieldDisplayName ? content.FieldDisplayName.split(',') : [];
        var mClassDisplayField = content.MClassDisplayField ? content.MClassDisplayField.split('|') : [];
        var classDisplayField = {
          Price: false,
          ProductCode: false,
          PackageSpec: false,
          BuyLimit: false,
          BarCode: false,
          PromotLadder: false,
          Sell: false
        };
        for (var i = 0; i < mClassDisplayField.length; i++) {
          if (mClassDisplayField[i] == 'Sell') {
            classDisplayField[mClassDisplayField[i]] = content.ShowProductSells;
          } else {
            classDisplayField[mClassDisplayField[i]] = true;
          }
        }
        // 快速下单页面为默认样式，不使用新的样式
        let AppQuickTemplateConfig = content.AppQuickTemplateConfig || {
          TemplateIndex: 0
        }
        that.setData({
          quantityDigits: content.QuantityDigits,
          priceDigits: content.PriceDigits,
          enableZeroStockBuy: content.EnableZeroStockBuy,
          NotShowProductNoneOffered: content.NotShowProductNoneOffered, // 是否不显示无货商品按钮
          spectStyle: content.GoodsDisplayMode,
          isScanty: content.IsScanty, //是否允许缺货登记
          decimalDigits: content.DecimalDigits,
          NoLoginShowPrice: content.NoLoginShowPrice, //0：建议零售价 1：不显示价格
          showRetailPrice: content.ShowRetailPrice,
          CartName: api.CartName || '购物车',
          FieldDisplayName: fieldDisplayName,
          ClassDisplayField: classDisplayField,
          IsGoodsTrading: content.IsGoodsTrading,
          GoodsUnitDisplayMode: content.GoodsUnitDisplayMode,
          ShowVendorName: content.ShowVendorName,
          FrontShowStockDetail: content.FrontShowStockDetail,
          AppQuickTemplateConfig: AppQuickTemplateConfig,
          BGColorForMobile: content.BGColorForMobile
        })
        that.getDataList()
      })
  },

  onAddCartCompleted(e) {
    let index = e.detail.idx
    let product = e.detail.product
    let productList = this.data.productList
    productList[index] = product
    this.setData({
      productList
    })
  },

  /**显示多规则 */
  onShowGoodsModal(e) {
    var that = this
    e = e.detail
    let {
      addr,
      priceDigits,
      quantityDigits,
      isScanty,
      productList
    } = this.data
    let product = productList[e.idx]
    that.fasterComponent.setData({
      item: product,
      isScanty: isScanty,
      quantityDigits: quantityDigits,
      priceDigits: priceDigits,
      areaCode: addr ? addr.code : '',
      addCompleted: function (goods) {
        that.onAddCartCompleted({
          detail: {
            product: goods,
            idx: e.idx
          }
        });
      }
    });
    that.fasterComponent.onShowGoodsModal(e)
  },

  bindUnfold(e) {
    let productList = this.data.productList
    productList[e.detail.idx].show = !productList[e.detail.idx].show
    this.setData({
      productList
    })
  },

  /*
   弹出缺货登记的层 
   */
  onShowScanty(e) {
    var that = this;
    var idx = e.detail.idx;
    let productList = this.data.productList
    var product = productList[idx]
    if (product.IsSingle == 0) {
      that.onShowGoodsModal({
        detail: {
          product: product,
          idx: idx
        }
      });
    } else {
      let unit_index = 0;
      for (let k = 0; k < product.AuxiliaryUnits.length; k++) {
        if (product.AuxiliaryUnits[k].Name == product.AuxUnit) {
          unit_index = k;
          break;
        }
      }
      product.ZIndex = unit_index;
      if (product.EnableSKUTranslated != 1) {
        let units = product.AuxiliaryUnits || [];
        product.productUnitText = detail.loadUnitContext(units, product.Unit);
      }
      that.outofstock.setData({
        scantyProduct: product,
      })
      that.outofstock.openScanyDialog(e);
    }
  },

  /**
   * 查看库存分布
   * @param {*} e 
   */
  showStockDistribution(e) {
    var idx = e.detail.idx
    let productList = this.data.productList
    var product = productList[idx]
    this.stockdistribution.setData({
      product: product
    })
    this.stockdistribution.showStockModal(e)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      productList: [],
      loaded: false,
      hasMore: true,
      pageIndex: 1
    })
    locked = true
    this.getDataList()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let {
      hasMore,
      pageIndex
    } = this.data
    if (!hasMore) {
      return
    }
    if (locked) {
      return
    }
    locked = true
    pageIndex += 1
    this.setData({
      pageIndex
    })
    this.getDataList()
  }
})